package com.cyzy.service.impl;

import com.cyzy.entity.User;
import com.cyzy.exception.BusinessException;
import com.cyzy.mapper.UserMapper;
import com.cyzy.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> getUsers(Integer username, String realName, String phone, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(userMapper.selectUsers(username, realName, phone, (pageNum-1)*pageSize, pageSize));
    }

    @Override
    public User getUserById(Integer id) {
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
        if (user == null || user.getId() == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 验证用户是否存在
        User existingUser = userMapper.selectById(user.getId());
        if (existingUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 如果密码为空，则不更新密码
        if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
            user.setPassword(null);
        }

        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Integer id) {
        if (id == null) {
            throw new BusinessException("用户ID不能为空");
        }

        // 验证用户是否存在
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        return userMapper.deleteById(id) > 0;
    }
}